var DBConfig = require('./config');
var mysql = require('mysql');
var pool = mysql.createPool(DBConfig);


const formatObject = function (res) {
    let _data = {};
    for (const key in res) {
        if (res.hasOwnProperty(key)) {
            const _item = res[key];
            var _key = key.replace(/\_(\w)/g, function (all, letter) {
                return letter.toUpperCase();
            });
            _data[_key] = _item;
        }
    };
    return _data;
};


var formatArray = function (res) {
    var data = [];
    for (let i = 0; i < res.length; i++) {
        const element = res[i];
        var _data = formatObject(element);
        data.push(_data);
    };
    return data;
};

module.exports = function query(sql, sqlParams, callback) {
    pool.getConnection(function (err, conn) {
        if (err) {
            callback(err, null, null);
        } else {
            conn.query(sql, sqlParams, function (qerr, vals, fields) {
                if (qerr) {
                    callback(qerr, null, null);
                } else {
                    callback(qerr, formatArray(vals), fields);
                }
            });
            conn.release(); // not work!!!
        };
    });
};


